package procesamientoDeVideo;

import java.util.ArrayList;
import java.util.Iterator;

import processing.core.PApplet;
import processing.core.PVector;
import processing.video.*;

public class Proyecto extends PApplet {

	private static final long serialVersionUID = 1L;
	private Capture cam;
	private ParticleSystem ps;
	private int conteo;

	
	public void setup() {

		size(640, 480);
		smooth();

		//Los parametros de PVector controlan la posicion de la manguera
		ps = new ParticleSystem(new PVector(width/2,10));
		cam = new Capture(this, width, height,24);
		conteo=0;
		loadPixels();
	}

	public void draw() 
	{
		if (cam.available()) 
		{
			cam.read();
			image(cam, 0, 0);
		}

		//el valor de "conteo" controla el flujo de salida de particulas.
		conteo++;
		if(conteo==20)
		{
			conteo=0;
			ps.addParticle();
		}
		ps.run();
	} 

	// A class to describe a group of Particles
	// An ArrayList is used to manage the list of Particles 
	private class ParticleSystem
	{
		private ArrayList<Particle> particles;
		private PVector origin;

		public ParticleSystem(PVector location) {
			origin = location.get();
			particles = new ArrayList<Particle>();
		}

		public void addParticle() {
			particles.add(new Particle(origin));
		}

		public void run() {
			Iterator<Particle> it = particles.iterator();
			while (it.hasNext()) {
				Particle p = it.next();
				p.run();
				if (p.isDead()) {
					it.remove(); 
				}
			}
		}
	}

	// A simple Particle class

	private class Particle {
		private PVector location;
		private PVector velocity;
		private PVector acceleration;
		private float lifespan;

		public Particle(PVector l) {
			acceleration = new PVector(0,(float) 0.05);
			velocity = new PVector(random(-2,2),random(0,0));
			location = l.get();
			lifespan = (float) 255.0;
		}

		public void run() {
			update();
			display();
		}

		// Method to update location
		public void update() {
			velocity.add(acceleration);
			location.add(velocity);
			lifespan -= 1.0;
		}

		// Method to display
		public void display() {
			
			//Las siguientes 2 lineas controlan el color de la gota
			stroke(51,102,255,lifespan);
			fill(51,102,255,lifespan);
			ellipse(location.x,location.y,8,8);
		}

		// Is the particle still useful?
		public boolean isDead() {
			if (lifespan < 0.0) {
				return true;
			} else {
				return false;
			}
		}
	}
}
